package com.zmx.patientend.view.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.bumptech.glide.Glide;
import com.google.android.material.tabs.TabLayout;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.bean.ZxingConfig;
import com.yzq.zxinglibrary.common.Constant;
import com.zmx.patientend.BaseActivity;
import com.zmx.patientend.R;
import com.zmx.patientend.fragment.InformationFragment;
import com.zmx.patientend.fragment.patient.CaseManagementFragment;
import com.zmx.patientend.fragment.patient.PhysicianListFragment;
import com.zmx.patientend.fragment.patient.PrescribingRecordFragment;
import com.zmx.patientend.okhttp.OkHttp3ClientManager;
import com.zmx.patientend.utils.AllUtil;
import com.zmx.patientend.view.util.CustomToast;
import com.zmx.patientend.view.util.MySharedPreferences;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * 程序猿：胖胖祥
 * 时 间：2020/9/19  15:00
 * 功 能：患者信息详情
 */
public class PatientMessageDetailsActivity extends BaseActivity {

    //需要的权限数组 读/写/相机
    private static String[] PERMISSIONS_STORAGE = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
    @BindView(R.id.release_quantity)
    TextView releaseQuantity;
    @BindView(R.id.release_quantity_text)
    TextView releaseQuantityText;
    @BindView(R.id.closing)
    TextView closing;
    @BindView(R.id.text_a)
    TextView text_a;
    @BindView(R.id.text_c)
    TextView text_c;
    @BindView(R.id.text_d)
    TextView text_d;
    @BindView(R.id.text_e)
    TextView text_e;
    @BindView(R.id.closing_text)
    TextView closingText;
    @BindView(R.id.order)
    TextView order;
    @BindView(R.id.yorder)
    TextView yorder;
    @BindView(R.id.yorder_text)
    TextView yorder_text;
    @BindView(R.id.order_text)
    TextView orderText;
    @BindView(R.id.step_number)
    TextView step_number;
    @BindView(R.id.get_address)
    TextView get_address;
    @BindView(R.id.relative_a)
    RelativeLayout relativeA;
    @BindView(R.id.relative_c)
    RelativeLayout relativeC;
    @BindView(R.id.relative_d)
    RelativeLayout relativeD;
    @BindView(R.id.relative_e)
    RelativeLayout relative_e;
    @BindView(R.id.bracelet)
    LinearLayout bracelet;
    @BindView(R.id.sh_layout)
    LinearLayout sh_layout;
    @BindView(R.id.sh_layout_a)
    LinearLayout sh_layout_a;

    private int REQUEST_CODE_SCAN = 1;

    private CircleImageView head;
    private TextView name, phone;
    private String s_name, s_head;

    static final int NUM_ITEMS = 3;
    private List<Fragment> fragmentList = new ArrayList<Fragment>();
    private String[] strings = new String[]{"在线问诊", "开方记录", "健康档案"};

    private String patient_id;

    private TextView address_text;
    private Button button;

    private boolean address_state = true;

    private Integer i_type = 0;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_patient_message_details;
    }

    @Override
    protected void initViews() {

        setToolbar(R.id.tool_bar);
        ButterKnife.bind(this);
        //跳转相机动态权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
        }

        button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                i_type = 0;
                getPulesStatus();

            }
        });

        patient_id = this.getIntent().getStringExtra("patient_id");

        Log.e("获取的id", "获取的id" + patient_id);

        head = findViewById(R.id.image_head);
        address_text = findViewById(R.id.address_text);
        name = findViewById(R.id.name);
        phone = findViewById(R.id.phone);

        address_text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (address_state) {

                    //页面返回时，弹出提示框，包括确认、取消按钮，提示文字
                    AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
                    builder.setTitle("选择添加手环方式");
                    builder.setNegativeButton("手动填写设备号", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            alert_label("输入设备号");

                        }
                    });
                    builder.setPositiveButton("扫描二维码", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //检查是否已经获得相机的权限
                            if (verifyPermissions(mActivity, PERMISSIONS_STORAGE[2]) == 0) {
                                ActivityCompat.requestPermissions(mActivity, PERMISSIONS_STORAGE, 3);
                            } else {
                                //已经有权限
                                Intent intent = new Intent(mActivity, CaptureActivity.class);
                                /*ZxingConfig是配置类
                                 *可以设置是否显示底部布局，闪光灯，相册，
                                 * 是否播放提示音  震动
                                 * 设置扫描框颜色等
                                 * 也可以不传这个参数
                                 * */
                                ZxingConfig config = new ZxingConfig();
                                config.setPlayBeep(true);//是否播放扫描声音 默认为true
                                config.setShake(true);//是否震动  默认为true
                                config.setDecodeBarCode(true);//是否扫描条形码 默认为true
                                config.setReactColor(R.color.colorAccent);//设置扫描框四个角的颜色 默认为白色
                                config.setFrameLineColor(R.color.colorAccent);//设置扫描框边框颜色 默认无色
                                config.setScanLineColor(R.color.colorAccent);//设置扫描线的颜色 默认白色
                                config.setFullScreenScan(false);//是否全屏扫描  默认为true  设为false则只会在扫描框中扫描
                                intent.putExtra(Constant.INTENT_ZXING_CONFIG, config);
                                startActivityForResult(intent, REQUEST_CODE_SCAN);
                            }
                        }
                    });
                    builder.show();

                }

            }
        });


        Bundle bundle = new Bundle();
        bundle.putString("patient_id", patient_id);
        PhysicianListFragment aof = new PhysicianListFragment();
        aof.setArguments(bundle);//数据传递到fragment中
        CaseManagementFragment cmf = new CaseManagementFragment();
        cmf.setArguments(bundle);//数据传递到fragment中
        PrescribingRecordFragment prf = new PrescribingRecordFragment();
        prf.setArguments(bundle);//数据传递到fragment中

        fragmentList.add(aof);
        fragmentList.add(prf);
        fragmentList.add(cmf);

        TabLayout tab_layout = findViewById(R.id.tab_layout);
        ViewPager viewPager = findViewById(R.id.viewPager);
        MyAdapter fragmentAdater = new MyAdapter(getSupportFragmentManager());
        viewPager.setAdapter(fragmentAdater);
        tab_layout.setupWithViewPager(viewPager);

        patient();


    }


    public void alert_label(String text) {

        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);

        LayoutInflater factory = LayoutInflater.from(this);//提示框
        final View view = factory.inflate(R.layout.dialog_edit, null);//这里必须是final的
        final EditText et = view.findViewById(R.id.editText);
        et.setHint(text);
        builder.setTitle(text);

        final AlertDialog dialog = builder.create();
        dialog.setView(view);

        dialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });

        dialog.setButton(DialogInterface.BUTTON_NEUTRAL, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog.show();

        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                if (!TextUtils.isEmpty(et.getText().toString())) {

                    binding(et.getText().toString());
                    dialog.dismiss();

                } else {

                    Toast("非法输入!");

                }

            }
        });


    }

    /**
     * 检查是否有对应权限
     *
     * @param activity   上下文
     * @param permission 要检查的权限
     * @return 结果标识
     */
    public int verifyPermissions(Activity activity, String permission) {
        int Permission = ActivityCompat.checkSelfPermission(activity, permission);
        if (Permission == PackageManager.PERMISSION_GRANTED) {

            return 1;
        } else {
            return 0;
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 1:

                    try {

                        Log.e("我是定位信息", "我是定位" + msg.obj.toString());

                        JSONObject object = new JSONObject(msg.obj.toString());

                        if (object.getInt("code") == 0) {
                            address_state = true;
                            address_text.setText("未绑定手环，点击绑定");
                            get_address.setVisibility(View.GONE);
                            sh_layout.setVisibility(View.GONE);
                            sh_layout_a.setVisibility(View.GONE);

                        } else {

                            address_state = false;

                            get_address.setVisibility(View.VISIBLE);
                            sh_layout.setVisibility(View.VISIBLE);
                            sh_layout_a.setVisibility(View.VISIBLE);

                            JSONObject data = object.getJSONObject("data");


                            JSONObject bt = data.getJSONObject("bt");
                            releaseQuantity.setText("体温" + bt.getString("temp") + "°C");
//                            releaseQuantityText.setText(bt.getString("tips"));
                            releaseQuantityText.setText("查看");

                            JSONObject bp = data.getJSONObject("bp");
                            order.setText("血压" + bp.getString("systolic") + "/" + bp.getString("diastolic"));
                            orderText.setText("查看");


                            JSONObject oxygen = data.getJSONObject("hr");
                            closing.setText("心率" + oxygen.getString("hr") + "次/分");
                            closingText.setText("查看");

                            JSONObject oxygens = data.getJSONObject("oxygen");
                            yorder.setText("血氧" + oxygens.getString("value") + "次/分");
                            yorder_text.setText("查看");

                            step_number.setText(data.getString("step") + "步");

                            JSONObject address = data.getJSONObject("address");
                            GeoCoder mSearch = GeoCoder.newInstance();
                            mSearch.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
                                @Override
                                public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

                                }

                                @Override
                                public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
                                    Log.e("打印转换后的地址", reverseGeoCodeResult.getAddress());

                                    address_text.setText("定位：" + reverseGeoCodeResult.getAddress());
                                    address_state = false;

                                }
                            });
                            //下面是传入对应的经纬度
                            mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(new LatLng(address.getDouble("latitude"), address.getDouble("longitude"))));

                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

                case 2:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        JSONObject data = object.getJSONObject("data");
                        Glide.with(mActivity).load(data.getString("avatar")).into(head);
                        s_head = data.getString("avatar");
                        name.setText(data.getString("name"));
                        s_name = data.getString("name");
                        phone.setText(data.getString("account"));

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                    break;

                case 3:

                    try {

                        JSONObject jsonObject = new JSONObject(msg.obj.toString());


                        if (jsonObject.getInt("code") == 1) {

                            Bundle bundles = new Bundle();

                            if (i_type == 0) {

                                bundles.putString("name", s_name);
                                bundles.putString("head", s_head);
                                bundles.putString("p_id", patient_id);
                                bundles.putString("data", jsonObject.getString("data"));
                                startActivity(PulseConditionActivity.class, bundles);

                            } else {

                                bundles.putString("p_id", patient_id);
                                startActivity(BraceletInformationActivity.class, bundles);

                            }

                        } else {

                            Toast(jsonObject.getString("msg"));

                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

                case 4:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        Toast(object.getString("msg"));

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                    break;

                case 5:

                    Toast("更新体温成功");

                    break;

                case 6:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        Toast(object.getString("msg"));
                        if (object.getInt("code") == 1) {
                            prevent();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                    break;
                case 7:

                    Toast("更新血氧成功");

                    break;


            }

        }
    };


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1 && resultCode == RESULT_OK) {

            if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
                if (data != null) {

                    String content = data.getStringExtra(Constant.CODED_CONTENT);
                    binding(content);

                }
            }
        }

        }


        public void binding(String devicel){

            List<String> l = new ArrayList<>();
            l.add(devicel);
            l.add(patient_id);

            //请求网络
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("sign", AllUtil.md5(sing(l)));
            params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
            params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
            params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
            params.put("cmd", "binding");
            params.put("data[devicel]", devicel);
            params.put("data[patient_id]", patient_id);
            OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/watch/", params, handler, 6, 404);

        }


        public void prevent () {

            List<String> l = new ArrayList<>();
            l.add(patient_id);
            //请求网络
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("sign", AllUtil.md5(sing(l)));
            params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
            params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
            params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
            params.put("cmd", "prevent");
            params.put("data[patient_id]", patient_id);
            OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/watch", params, handler, 1, 404);

        }

        /**
         * 查询患者资料
         */
        public void patient () {

            List<String> ls = new ArrayList<>();
            ls.add(patient_id);
            //请求网络
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("sign", AllUtil.md5(sing(ls)));
            params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
            params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
            params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
            params.put("cmd", "patient");
            params.put("data[patient_id]", patient_id);
            OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/app/", params, handler, 2, 404);

        }

        /**
         * 检测脉象
         */
        public void getPulesStatus () {

            List<String> ls = new ArrayList<>();
            ls.add("5");
            ls.add(patient_id);
            //请求网络
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("sign", AllUtil.md5(sing(ls)));
            params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
            params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
            params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
            params.put("cmd", "getPulesStatus");
            params.put("data[patient_id]", patient_id);
            params.put("data[minute]", "5");
            OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/watch", params, handler, 3, 404);

        }


        @OnClick({R.id.relative_a, R.id.get_address,R.id.relative_c, R.id.relative_d,R.id.text_e, R.id.text_a, R.id.text_c, R.id.text_d, R.id.bracelet,R.id.relative_e})
        public void onViewClicked (View view){
            Bundle bundle = new Bundle();
            switch (view.getId()) {


                case R.id.relative_a:

                    bundle.putString("logo", "a");
                    bundle.putString("p_id", patient_id);
                    startActivity(BodyTemperatureActivity.class, bundle);


                    break;

                case R.id.relative_c:

                    bundle.putString("logo", "b");
                    bundle.putString("p_id", patient_id);
                    startActivity(BodyTemperatureActivity.class, bundle);

                    break;
                case R.id.relative_d:

                    bundle.putString("logo", "d");
                    bundle.putString("p_id", patient_id);
                    startActivity(BodyTemperatureActivity.class, bundle);
                    break;

                case R.id.relative_e:

                    bundle.putString("logo", "b");
                    bundle.putString("p_id", patient_id);
                    startActivity(BodyTemperatureActivity.class, bundle);

                    break;

                case R.id.text_a:

                    Toast("获取中...");
                    getBloodPressures();

                    break;

                case R.id.text_c:

                    Toast("获取中...");
                    getHeartRates();
                    break;
                case R.id.text_d:

                    Toast("获取中....");
                    getBloodPressure();

                    break;

                case R.id.text_e:

                    Toast("获取中....");
                    getHeartRatess();

                    break;

                case R.id.bracelet:
                    i_type = 1;
                    getPulesStatus();

                    break;

                case R.id.get_address:
                    getLocation();
                    break;

            }

        }

        @Override
        protected void onResume () {
            super.onResume();

            Log.e("回来了", "回来了");
            prevent();

        }

        public class MyAdapter extends FragmentPagerAdapter {
            public MyAdapter(FragmentManager fm) {
                super(fm);
            }

            @Override
            public int getCount() {
                return NUM_ITEMS;
            }

            @Override
            public Fragment getItem(int position) {
                return fragmentList.get(position);
            }

            @Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                return strings[position];
            }
        }

        /**
         * 心率
         */
        public void getHeartRates () {

            List<String> ls = new ArrayList<>();
            ls.add(patient_id);
            //请求网络
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("sign", AllUtil.md5(sing(ls)));
            params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
            params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
            params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
            params.put("cmd", "getHeartRates");
            params.put("data[patient_id]", patient_id);
            OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/watchApi", params, handler, 4, 404);

        }

    public void getHeartRatess () {

        List<String> ls = new ArrayList<>();
        ls.add(patient_id);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getHeartRates");
        params.put("data[patient_id]", patient_id);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/watchApi", params, handler, 7, 404);

    }



    /**
         * 血压
         */
        public void getBloodPressure () {

            List<String> ls = new ArrayList<>();
            ls.add(patient_id);
            //请求网络
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("sign", AllUtil.md5(sing(ls)));
            params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
            params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
            params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
            params.put("cmd", "getBloodPressure");
            params.put("data[patient_id]", patient_id);
            OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/watchApi", params, handler, 4, 404);

        }


    //假数据
    public void getBloodPressures () {

        List<String> ls = new ArrayList<>();
        ls.add(patient_id);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getBloodPressure");
        params.put("data[patient_id]", patient_id);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/watchApi", params, handler, 5, 404);

    }

    //获取定位
    public void getLocation() {

        List<String> ls = new ArrayList<>();
        ls.add(patient_id);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getLocation");
        params.put("data[patient_id]", patient_id);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/watchApi", params, handler, 4, 404);

    }

    }
